<?php
/**
 * 支付宝有密退款
 * @author chenlisong E-mail:chenlisong1021@163.com 
 * @version 创建时间：2016年9月21日 下午4:15:25 
 * 类说明
 */
class AlipayAction extends Action{
	
	public function _initialize(){
		$this->param = $_REQUEST;
		vendor('Alipay.Corefunction');
		vendor('Alipay.Md5function');
		vendor('Alipay.Notify');
		vendor('Alipay.Submit');
	}
	
	/**
	 * 支付宝有密退款
	 * 单笔数据集格式为：第一笔交易退款数据集#第二笔交易退款数据集#第三笔交易退款数据集…#第N笔交易退款数据集；
	 * 交易退款数据集的格式为：原付款支付宝交易号^退款总金额^退款理由；
	 * 不支持退分润功能。
	 * @return string
	 */
	public function cancelOrderAli(){
		$Order = M('Order');$OrderDetails = M('OrderDetails');
		$orderId = $_POST['id'];
		if(!isset($orderId)){
			$this->ajaxReturn(0,'参数错误！',0);
		}
		$info = $Order->where('id = '.$orderId)->find();
		if($info['status'] != 0){
			$this->ajaxReturn(0,'订单状态错误，无法操作！',0);
		}
		//组装签名
		$parameter = array(
				"service" => "refund_fastpay_by_platform_pwd",
				"partner" => C('alipay_app_config.partner'),
				"_input_charset"	=> 'utf-8',
				"notify_url"	=> C('APP_ALIPAY_ORDER_REFUND_NOTIFY_URL'),
				"seller_email"	=> C('APP_ALIPAY_SELLER_ID'),
				"refund_date"	=> date("Y-m-d H:i:s",time()),
				"batch_no"	=> date('Ymdhis').rand(10,99),//退款批次号
				"batch_num"	=> 1,//退款笔数
				"detail_data"	=> $info['pay_code']."^".($info['real_price'] + $info['mail_fee'])."^协商退款",
				"sign_type"	=> 'md5',//退款笔数
		);
		//建立请求
		$alipay_config = C('alipay_config');
		$alipay_config['sign_type'] = 'md5';
		$alipaySubmit = new AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter,"post", "正在跳转到支付宝...");
		$this->ajaxReturn($html_text,"请求成功！",1);
	}
	
	/**
	 * 处理订单
	 */
	public function notifyOrderRetund(){
		$alipay_config = C('alipay_config');
		//计算得出通知验证结果
		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if($verify_result) {
			//验证成功
			$Order = M('Order');$ShopProduct = M("ShopProduct");$ShopAttributeValues = M("ShopAttributeValues");$OrderDetails = M('OrderDetails');
			$batch_no = $_POST['batch_no'];//批量退款数据中转账成功的笔数
			$success_num = $_POST['success_num'];//批量退款数据中的详细信息
			$result_details = $_POST['result_details'];//批量退款数据中的详细信息
			$result_details = explode("^", $result_details);
			$code = $result_details[0];//支付宝交易号
			$price = $result_details[1];
			$where['pay_code'] = $code;
			$info = $Order->where($where)->find();
			//推送
			$this->insertNotice($info['user_id'], "您的申请退款已成功！", $info['code']);
			//处理订单
			$data['flag'] = 1;
			$data['return_time'] = time();
			$data['status'] = -2;
			$Order->where($where)->save($data);

			//库存恢复
			$orderDetails = $OrderDetails->where(array('order_code'=>$info['code'],'flag'=>1))->select();
			$querySql_s = 'SET num = CASE product_id ';
			$queryIds_s = "";

			$querySql_1 = 'SET num = CASE id ';
			$queryIds_1 = "";

			foreach ($orderDetails as $pk => $pv) {
				$sellNum = $pv['num'];
				//组装扣除商品数量sql
				if ($pv['attribute_values'] != "") {
					$querySql_1 .= ' WHEN ' . $pv['attr_values_id'] . ' THEN num +' . $sellNum . " ";
					$queryIds_1 .= $pv['attr_values_id'] . ",";
				} else {
					$querySql_s .= ' WHEN ' . $pv['product_id'] . ' THEN num +' . $sellNum . " ";
					$queryIds_s .= $pv['product_id'] . ",";
				}

			}

			if ($queryIds_1 != '') {
				$querySql_1 .= ' END ';
				$queryIds_1 = substr($queryIds_1, 0, strlen($queryIds_1) - 1);
				$querySql_1 .= 'where flag=1 and id in (' . $queryIds_1 . ') and shop_id='.$info['shop_id'];
			}

			if ($queryIds_s != '') {
				$querySql_s .= ' END ';
				$queryIds_s = substr($queryIds_s, 0, strlen($queryIds_s) - 1);
				$querySql_s .= 'where  flag=1 and product_id in (' . $queryIds_s . ') and shop_id=' . $info['shop_id'];
			}

			//恢复规格库存
			if ($queryIds_1 != '') {
				$ShopAttributeValues->execute('update __TABLE__ ' . $querySql_1);
			}

			//恢复店铺商品库存
			if ($queryIds_s != '') {
				$ShopProduct->execute('update __TABLE__ ' . $querySql_s);
			}
			echo "success";
		}else {
			echo "fail";
		}
	}
	

	/**
	 * 新增消息
	 * 只新增个人订单消息
	 */
	private function insertNotice($userId,$message,$ambulance){
		$Notice = M('Notice');$User = M('User');
		$jpushId = $User->where('id = '.$userId)->getField('jpush_id');
		if(!empty($jpushId)){
			$data['type'] = 1;
			$data['user_id'] = $userId;
			$data['message'] = $message;
			$data['ambulance'] = $ambulance;
			$data['create_time'] = time();
			$Notice->add($data);
		}
		return true;
	}
}